/**
 * 作用：编译合约
 * fs 文件模块
 * path 路径模块
 * solc solidity模块
 * contractPath 合约路径
 */
const fs = require('fs');
const path = require('path');
const solc = require('solc');

const contractPath = path.resolve(__dirname, '../contracts/blockChain.sol');

const source = fs.readFileSync(contractPath, 'utf-8').toString();
let input = {
  language: 'Solidity',
  sources: {
    'blockChain.sol': {
      content: source
    }
  },
  settings: {
    outputSelection: {
      '*': {
        '*': [ '*' ]
      }
    }
  }
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
if(Array.isArray(output.errors) && output.errors.length>0) {
  console.log(output.errors[0]);
}else {
  Object.keys(output.contracts['blockChain.sol']).forEach( (contractName) => {
    const filePath = path.resolve(__dirname, `../src/compiled/${contractName}.json`);
    fs.writeFileSync(filePath, JSON.stringify(output.contracts['blockChain.sol'][contractName]));
    console.log(`${filePath} bingo`);
  });
}